<?php

namespace plugin\voice\app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class StaticFile implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response{
        if (strpos($request->path(), '/.') !== false) {
            return response('<h1>403 forbidden</h1>', 403);
        }
        $response = $next($request);
        return $this->cors($request, $response);
    }
    
    protected function cors(Request $request, Response $response)
    {
        if (method_exists($response, 'exception') && $exception = $response->exception()) {
            $code = $exception->getCode() ?: 1;
            $msg = $exception->getMessage();
            $response = $request->expectsJson() ? json([
                'code' => $code,
                'msg' => $msg,
                'error' => ['message' => $msg],
                'data' => [],
                'traces' => config('plugin.voice.app.debug') ? $exception->getTraceAsString() : ''
            ]) : $response;
        }
        return $response->withHeaders([
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
        ]);
    }
}
